//
//  SWCameraViewController.m
//  ShiWu
//
//  Created by  on 2022/7/27.
//

#import "SWCameraViewController.h"
#import "SWDetailViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface SWCameraViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (weak, nonatomic) IBOutlet UIView *bg_top;
@property (weak, nonatomic) IBOutlet UIView *bg_bottom;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *lineCenterX1;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *lineCenterX2;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *lineCenterX3;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *lineCenterX4;
@property (weak, nonatomic) IBOutlet UIImageView *layerImage;

@property (nonatomic, strong) AVCaptureDevice *device;
//AVCaptureDeviceInput 代表输入设备，他使用AVCaptureDevice 来初始化
@property (nonatomic, strong) AVCaptureDeviceInput *input;
//输出图片
@property (nonatomic ,strong) AVCaptureStillImageOutput *imageOutput;
//session：由他把输入输出结合在一起，并开始启动捕获设备（摄像头）
@property (nonatomic, strong) AVCaptureSession *session;
//图像预览层，实时显示捕获的图像
@property (nonatomic ,strong) AVCaptureVideoPreviewLayer *previewLayer;
@property (nonatomic, assign) ShiWuType type;

@property (weak, nonatomic) IBOutlet UIImageView *resultPhoto;
@end

@implementation SWCameraViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initCamera];
    self.bg_bottom.backgroundColor = [UIColor colorWithHexString:@"#333333" alpha:0.2];
    // Do any additional setup after loading the view from its nib.
}

- (void)initCamera
{
    self.device = [self cameraWithPosition:AVCaptureDevicePositionBack];
    self.input = [[AVCaptureDeviceInput alloc] initWithDevice:self.device error:nil];
    self.imageOutput = [[AVCaptureStillImageOutput alloc] init];
    self.session = [[AVCaptureSession alloc] init];
    self.session.sessionPreset = AVCaptureSessionPreset640x480;
    //输入输出设备结合
    if ([self.session canAddInput:self.input]) {
        [self.session addInput:self.input];
    }
    if ([self.session canAddOutput:self.imageOutput]) {
        [self.session addOutput:self.imageOutput];
    }
    //预览层的生成
    self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
    self.previewLayer.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-220);
    self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    [self.view.layer addSublayer:self.previewLayer];
    [self.view bringSubviewToFront:self.bg_top];
    //设备取景开始
    [self.session startRunning];
    if ([_device lockForConfiguration:nil]) {
        //自动白平衡,但是好像一直都进不去
        if ([_device isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeAutoWhiteBalance]) {
            [_device setWhiteBalanceMode:AVCaptureWhiteBalanceModeAutoWhiteBalance];
        }
        [_device unlockForConfiguration];
    }
}

- (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition)position{
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for ( AVCaptureDevice *device in devices )
        if ( device.position == position ){
            return device;
        }
    return nil;
}
- (void)photoBtnDidClick
{
    AVCaptureConnection *conntion = [self.imageOutput connectionWithMediaType:AVMediaTypeVideo];
    if (!conntion) {
        NSLog(@"拍照失败!");
        return;
    }
    [self.imageOutput captureStillImageAsynchronouslyFromConnection:conntion completionHandler:^(CMSampleBufferRef  _Nullable imageDataSampleBuffer, NSError * _Nullable error) {
        if (imageDataSampleBuffer == nil) {
            return ;
        }
        NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
        self.resultPhoto.image = [UIImage imageWithData:imageData];
        [self shibie];
        [self.session stopRunning];
    }];
}
- (void)changeCamera{
    NSUInteger cameraCount = [[AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo] count];
    if (cameraCount > 1) {
        NSError *error;
        //给摄像头的切换添加翻转动画
        CATransition *animation = [CATransition animation];
        animation.duration = .5f;
        animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        animation.type = @"oglFlip";
        
        AVCaptureDevice *newCamera = nil;
        AVCaptureDeviceInput *newInput = nil;
        //拿到另外一个摄像头位置
        AVCaptureDevicePosition position = [[_input device] position];
        if (position == AVCaptureDevicePositionFront){
            newCamera = [self cameraWithPosition:AVCaptureDevicePositionBack];
            animation.subtype = kCATransitionFromLeft;//动画翻转方向
        }
        else {
            newCamera = [self cameraWithPosition:AVCaptureDevicePositionFront];
            animation.subtype = kCATransitionFromRight;//动画翻转方向
        }
        //生成新的输入
        newInput = [AVCaptureDeviceInput deviceInputWithDevice:newCamera error:nil];
        [self.previewLayer addAnimation:animation forKey:nil];
        if (newInput != nil) {
            [self.session beginConfiguration];
            [self.session removeInput:self.input];
            if ([self.session canAddInput:newInput]) {
                [self.session addInput:newInput];
                self.input = newInput;
                
            } else {
                [self.session addInput:self.input];
            }
            [self.session commitConfiguration];
            
        } else if (error) {
            NSLog(@"toggle carema failed, error = %@", error);
        }
    }
}
- (void)openAlbum
{
    UIImagePickerController *vc = [[UIImagePickerController alloc] init];
    vc.delegate = self;
    vc.allowsEditing = YES;
    vc.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    vc.modalPresentationStyle = UIModalPresentationOverFullScreen;
    [self presentViewController:vc animated:YES completion:nil];
}
- (IBAction)actionForBtn:(UIButton *)sender {
    switch (sender.tag) {
        case 200:
        case 201:
        case 202:
        case 203:{
            for (UIControl *control in [self.bg_bottom subviews]) {
                if ([control isKindOfClass:[UIButton class]]) {
                    UIButton *btn = (UIButton *)control;
                    if (btn.tag == sender.tag) {
                        btn.selected = YES;
                        self.lineCenterX1.active = btn.tag == 200;
                        self.lineCenterX2.active = btn.tag == 201;
                        self.lineCenterX3.active = btn.tag == 202;
                        self.lineCenterX4.active = btn.tag == 203;
                        self.type = sender.tag - 200 + 1;
                    }else{
                        btn.selected = NO;
                    }
                }
            }
        }
            break;
        case 204:{///相册
            [self openAlbum];
        }
            break;
        case 205:{///拍照
            [self photoBtnDidClick];
        }
            break;
        case 206:{///反转摄像头
            [self changeCamera];
        }
            break;
        case 207:{///闪光灯
            if ([self.device hasFlash]) {
                [self.device lockForConfiguration:nil];
                sender.selected = !sender.selected;
                [self.device setFlashMode:sender.selected ? AVCaptureFlashModeOn : AVCaptureFlashModeOff];
                [self.device unlockForConfiguration];
            }
        }
            break;
        case 208:{///返回按钮
            [self dismissViewControllerAnimated:YES completion:nil];
        }
            break;
        default:
            break;
    }
}

- (void)shibie
{
    [SWTool swIMG:self.resultPhoto.image type:self.type success:^(NSDictionary * _Nonnull dict) {
        if (dict != nil) {
            SWDetailViewController *vc = [[SWDetailViewController alloc] init];
            BaseNavigationController *navc = [[BaseNavigationController alloc] initWithRootViewController:vc];
            vc.IMG = self.resultPhoto.image;
            vc.dict = dict;
            navc.modalPresentationStyle = UIModalPresentationFullScreen;
            [self presentViewController:navc animated:YES completion:^{
                self.resultPhoto.image = nil;
                [self.session startRunning];
            }];
        }
    }];
}
#pragma mark - UIImagePickerControllerDelegate / UINavigationControllerDelegate
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info
{
    UIImage *img = [info valueForKey:UIImagePickerControllerEditedImage];
    NSData *imageData = UIImageJPEGRepresentation(img, 0.5);
    self.resultPhoto.image = [UIImage imageWithData:imageData];
    [picker dismissViewControllerAnimated:YES completion:^{
        [self shibie];
    }];
}
@end
